% Copyright (c) 2020 NVI, Inc.
%
% This file is part of VLBI Field System
% (see http://github.com/nvi-inc/fs).
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.

function mask=find_mask(grid,level,azc,azs,elc,els)
%generate mask from holog data grid generated by holog.m
%
%input:
% grid  = rectangular matrix of data
% level = mask threshold
% azc   = center of az range
% azs   - az step size
% elc   = center of el range
% els   = el step size
%
%output:
% mask -  vector of [az,el,...,final], odd positions are azs, even are els
%         if final value is an az,
%           then el are step heights between the adjacent az values
%         if final value is an el,
%           then az,el pairs define endpoints of connected line segments

%turn in to grid of 0 and 1s, above and below threshold
grid=grid<level;
[rows,cols]=size(grid);
x=[];
y=[];
%find the edges using indices
for k = [1:cols]
    for j= [rows:-1:1]
        if(grid(j,k) == 0)
            x=[x,k];    
            y=[y,j];
            break;            
        elseif(j==1)
            x=[x,k];
            y=[y,0];
        end
    end
end
%build the mask
% working with integers so we can do exact comparisons
len=length(x);
mask=[x(1)];
for i = [2:len]
    if(y(i)>=y(i-1))
        mask=[mask,y(i),x(i)];
    else  % if(y(i)<y(i-1))
        mask=[mask,y(i-1),x(i)];
    end
end
%remove redundant elevation entries, only one pass needed
% working with integers so we can do exact comparisons
len=length(mask);
mask2=mask([1:2]);
for i = [4:2:len-1]
    if(mask(i)~=mask2(end))
        mask2=[mask2,mask(i-1),mask(i)];
    end
end
mask=[mask2,mask(end)];
%convert to az and el, now real numers are okay
az_start=azc-azs*(1+fix(cols/2));
el_start=elc-els*fix(rows/2); %one higher to start with
for i=[1:2:length(mask)]
    mask(i)=az_start+mask(i)*azs;
    if(i<length(mask))
        mask(i+1)=el_start+mask(i+1)*els;
    end
end
